import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/api/api_service.dart';
import 'package:flutter_app/model/coin_rank_bean.dart';
import 'package:flutter_app/res/strings.dart';
import 'package:flutter_app/widget/my_circular_progress_indicator.dart';

class IntegralRankPage extends StatefulWidget {
  @override
  IntegralRankPageState createState() => new IntegralRankPageState();
}

class IntegralRankPageState extends State<IntegralRankPage> {
  List<Rank> _coinRankList = List();

  int _pageNumber = 1;
  bool _isLoadAll = false;

  void _getRankList(int page) {
    ApiService().getCoinRankData(page, (CoinRankBean coinRankBean) {
      setState(() {
        if (coinRankBean.data != null) {
          _isLoadAll = coinRankBean.data.over;
          _coinRankList.addAll(coinRankBean.data.ranks);
        }
        if (_isLoadAll) {
          _coinRankList.add(null);
        }
      });
    });
  }

  @override
  void initState() {
    _getRankList(_pageNumber);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('积分排行榜'),
        ),
        body: (_coinRankList.length == 0)
            ? Center(
                child: MyCircularProgressIndicator(),
              )
            : ListView.builder(
                itemBuilder: (context, index) {
                  if (index == _coinRankList.length - 1) {
                    if (!_isLoadAll) {
                      _getRankList(_pageNumber++);
                      return MyCircularProgressIndicator();
                    } else {
                      return Container(
                        padding: EdgeInsets.all(5),
                        alignment: Alignment.center,
                        child: Text(Strings.GET_BOTTOM_CN),
                      );
                    }
                  }
                  return _integralItem(_coinRankList[index]);
                },
                itemCount: _coinRankList.length,
              ));
  }

  Widget _integralItem(Rank rank) {
    return Container(
      padding: EdgeInsets.all(15),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(child: Text("第${rank.rank}名")),
              Expanded(
                  child: Text(
                rank.username,
                style: TextStyle(fontSize: 16),
                textAlign: TextAlign.center,
              )),
              Expanded(child: Text("${rank.level}级",textAlign: TextAlign.center,))
            ],
          ),
          SizedBox(height: 5),
          Container(
            padding: EdgeInsets.only(top: 10),
            height: 1,
            color: Colors.grey,
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}
